# coding:utf-8
from PySide6.QtCore import QPoint, QRect, Property, QSize
from qfluentwidgets import FlowLayout, VBoxLayout


class GridLayout(FlowLayout):
    def __init__(self, parent=None):
        super().__init__(parent, False, False)
        self._itemMinWidth = 300

    def setItemMinimumWidth(self, width: int):
        self._itemMinWidth = width
        self._doLayout(self.geometry(), True)

    def getItemMinimumWidth(self):
        return self._itemMinWidth

    def _doLayout(self, rect: QRect, move: bool):
        margin = self.contentsMargins()
        left = rect.x() + margin.left()
        top = rect.y() + margin.top()

        spaceX = self.horizontalSpacing()
        spaceY = self.verticalSpacing()
        availableWidth = rect.width() - left - margin.right() + spaceX
        columns = max(1, (availableWidth + spaceX) // (self.itemMinimumWidth + spaceX))
        itemWidth = int((availableWidth - (columns - 1) * spaceX) / columns)
        columnHeights = [top] * columns

        for i, item in enumerate(self._items):
            if item.widget() and not item.widget().isVisible() and self.isTight:
                continue
            widget = item.widget()
            than = widget.height() / widget.width()  # 宽高比
            height = int(itemWidth * than)
            # height = widget.height()
            column = min(columnHeights.index(min(columnHeights)), columns - 1)
            x = left + column * (itemWidth + spaceX)
            y = columnHeights[column]
            if move:
                target = QRect(QPoint(x, y), QSize(itemWidth, height))
                item.setGeometry(target)
            columnHeights[column] += height + spaceY
        return top + max(columnHeights) + margin.bottom() - rect.y()

    itemMinimumWidth = Property(int, getItemMinimumWidth, setItemMinimumWidth)
